<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/26
 * Time: 9:55
 */
namespace backend\models;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\imagine\Image;

class Product extends  ActiveRecord
{

    public function rules()
    {
        return [
            ['title', 'required', 'message' => '标题不能为空'],
            ['descr', 'required', 'message' => '描述不能为空'],
            ['cateid', 'required', 'message' => '分类不能为空'],
            ['price', 'required', 'message' => '单价不能为空'],
            [['price','saleprice'], 'number', 'min' => 0.01, 'message' => '价格必须是数字'],
            ['num', 'integer', 'min' => 0, 'message' => '库存必须是数字'],
            [['issale','ishot', 'pics', 'istui'],'safe'],
            [['cover'], 'required'],
//            [['pics','cover'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'cateid' => '分类名称',
            'title'  => '商品名称',
            'descr'  => '商品描述',
            'price'  => '商品价格',
            'ishot'  => '是否热卖',
            'issale' => '是否促销',
            'saleprice' => '促销价格',
            'num'    => '库存',
            'cover'  => '图片封面',
            'pics'   => '商品图片',
            'ison'   => '是否上架',
            'istui'   => '是否推荐',
        ];
    }
    public function upload()
    {
        if($this->validate())
        {
            $pics= []  ;
            foreach ($this->pics as $key => $img)
            {
                $img->saveAs('..\\..\\uploads\pics\\' . $img->baseName . '.' . $img->extension);
                Image::thumbnail('..\\..\\uploads\pics\\' . $img->baseName . '.' . $img->extension,100,100,\Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET)->save('..\\..\\uploads\pics\\' . $img->baseName . '-min.' . $img->extension,['quality' => 100]);
                Image::thumbnail('..\\..\\uploads\pics\\' . $img->baseName . '.' . $img->extension,300,300,\Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET)->save('..\\..\\uploads\pics\\' . $img->baseName . '-mid.' . $img->extension,['quality' => 100]);
                $pics[$key]='..\\..\\uploads\pics\\' . $img->baseName . '.' . $img->extension;
            }

            $this->cover->saveAs('..\\..\\uploads\cover\\' . $this->cover->baseName . '.' . $this->cover->extension);
            Image::thumbnail('..\\..\\uploads\cover\\' . $this->cover->baseName . '.' . $this->cover->extension,100,100,\Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET)->save('..\\..\\uploads/cover\\' . $this->cover->baseName . '-min.' . $this->cover->extension,['quality' => 100]);
            $cover = '..\\..\\uploads\cover\\' . $this->cover->baseName . '.' . $this->cover->extension;
            return ['cover'=>$cover,'pics'=>json_encode($pics)];
        } else {
            return false;
        }
    }
}